<template>
  <a-drawer :title="labelTitle" width="100%" :visible="modalVisible"
    :body-style="{ paddingBottom: '80px', paddingRight: '20px' }" @close="handleCancel">
    <splitpanes class="default-theme" @resize="resize" @resized="resized">
      <pane min-size="25" size="40">
        <a-tabs default-active-key="1" style="margin: 20px 20px">
          <a-tab-pane key="1" tab="申请人">
            <a-table :scroll="{ x: 600, y: 550 }" :columns="applicantColumns" :data-source="applylist"
              :pagination="false">
              <span slot="index" slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span slot="genderSlot" slot-scope="text, record">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ genderLable(record.gender) }}</span>
                  </template>
                  {{ genderLable(record.gender) }}
                </a-tooltip>
              </span>
              <span slot="nationSlot" slot-scope="text, record">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ nationLable(record.nation) }}</span>
                  </template>
                  {{ nationLable(record.nation) }}
                </a-tooltip>
              </span>
              <span slot="addrSlot" slot-scope="text, record" class="beyond_hiding">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ record.addr }}</span>
                  </template>
                  {{ record.addr }}
                </a-tooltip>
              </span>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="申请人（法人或者其他组织）" force-render>
            <a-table :scroll="{ x: 800, y: 550 }" :columns="enterpriseColumns" :data-source="aplentlist"
              :pagination="false">
              <span slot="index" slot-scope="text, record, index">
                {{ index + 1 }}
              </span>

              <span slot="nameSlot" slot-scope="text, record" class="beyond_hiding">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ record.name }}</span>
                  </template>
                  {{ record.name }}
                </a-tooltip>
              </span>

              <span slot="addrSlot" slot-scope="text, record" class="beyond_hiding">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ record.addr }}</span>
                  </template>
                  {{ record.addr  }}
                </a-tooltip>
              </span>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="3" tab="第三人" force-render>
            <a-table :scroll="{ x: 800, y: 550 }" :columns="thirdColumns" :data-source="thirdperlist" :pagination="false">
              <span slot="index" slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span slot="genderSlot" slot-scope="text, record">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ genderLable(record.gender) }}</span>
                  </template>
                  {{ genderLable(record.gender) }}
                </a-tooltip>
              </span>
              <span slot="nationSlot" slot-scope="text, record">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ nationLable(record.nation) }}</span>
                  </template>
                  {{ nationLable(record.nation) }}
                </a-tooltip>
              </span>
              <span slot="nameSlot" slot-scope="text, record" class="beyond_hiding">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ record.name }}</span>
                  </template>
                  {{ record.name }}
                </a-tooltip>
              </span>

              <span slot="addrSlot" slot-scope="text, record" class="beyond_hiding">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ record.addr }}</span>
                  </template>
                  {{ record.addr  }}
                </a-tooltip>
              </span>
            </a-table>
          </a-tab-pane>
        </a-tabs>

        <a-form-model ref="caseHandleDecisionReject" :rules="rules" :model="infoForm" style="margin: 20px 20px">
          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="被申请人">
            <a-input disabled v-model="targetName" @blur="previewDecisionDoc" />
          </a-form-model-item>
          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="案由" prop="cause" >
            <a-textarea v-model="infoForm.cause" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入案由"  @blur="previewDecisionDoc" />
          </a-form-model-item>
          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="申请人请求" prop="aplrequest" >
            <a-textarea v-model="infoForm.aplrequest" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入申请人请求"  @blur="previewDecisionDoc" />
          </a-form-model-item>
          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="申请人称" prop="illustrate" >
            <a-textarea v-model="infoForm.illustrate" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入申请人称"  @blur="previewDecisionDoc" />
          </a-form-model-item>

          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="被申请人答复称" prop="reply" >
            <a-textarea v-model="infoForm.reply" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入被申请人答复称"  @blur="previewDecisionDoc" />
          </a-form-model-item>

          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="第三人称" prop="thirequest" 
            v-show="isShowThird">
            <a-textarea v-model="infoForm.thirequest" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="第三人称"  @blur="previewDecisionDoc"/>
          </a-form-model-item>

          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="经审理查明" prop="finding" >
            <a-textarea v-model="infoForm.finding" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入经审理查明"  @blur="previewDecisionDoc" />
          </a-form-model-item>

          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="本机关认为" prop="think" >
            <a-textarea v-model="infoForm.think" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入本机关认为"  @blur="previewDecisionDoc"/>
          </a-form-model-item>

          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="申请意见" prop="describe" >
            <a-textarea v-model="infoForm.describe" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入申请意见"  @blur="previewDecisionDoc" />
          </a-form-model-item>

          <a-form-model-item :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" label="是否符合行政诉讼受案范围">
            <a-radio-group v-model="radioVal" @change="onChangeRadio">
              <a-radio :value="true"> 符合 </a-radio>
              <a-radio :value="false"> 不符合 </a-radio>
            </a-radio-group>
          </a-form-model-item>

          <a-form-model-item :label-col="labelCol" v-show="isShowStatement" :wrapper-col="wrapperCol" label="符合描述"
            prop="statement" >
            <a-textarea v-model="infoForm.statement" allow-clear :maxLength="3000" :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入符合描述"  @blur="previewDecisionDoc"/>
          </a-form-model-item>
        </a-form-model>
      </pane>
      <pane min-size="25">
        <div class="pane_right">
          <div ref="file" :loading="previewLoading" element-loading-text="拼命加载中" 
            element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" 
          style="height:90%;overflow-y:auto;"></div>
        </div>
      </pane>
    </splitpanes>

    <div class="button-div">
      <a-button style="margin-right: 20px" @click="handleCancel"> 取消 </a-button>
      <!-- <a-button style="margin-right: 20px" @click="previewDecisionDoc"> 取消 </a-button> -->
      <a-button type="primary" icon="save" @click="onSubmit" :loading="loading"> 提交 </a-button>
    </div>
  </a-drawer>
</template>
<script>
import { startBusinessProced, previewDecisionDoc } from '@/api/accept/business_Approve'
import { Tp_decision, Tp_decisionValue } from '@/enumeration/Tp_decision'
import { getThirdPerson } from '@/api/accept/apl_thirdper'
import { getApplicantlist } from '@/api/accept/apl_applicant'
import { Tp_applicantValue } from '@/enumeration/Tp_applicant'
import { Tp_genderList } from '@/enumeration/Tp_gender'
import { Tp_nationList } from '@/enumeration/Tp_nation'
import { getReviewList } from '@/api/accept/apl_admreview'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { renderAsync } from 'docx-preview';
import {CaseHandleDecisionMixin} from  '@/views/handleCase/CaseHandleDecisionMixin'
export default {
  mixins: [CaseHandleDecisionMixin],
  data() {
    return {
      infoForm: {
        applyid: '', // applyid
        proctype: '', // 操作分类
        userid: '',
        username: '',
        processinstanceid: '',
        cause: '', // 案由
        describe: '', // 行政复议申请
        aplrequest: '', // 申请人请求
        illustrate: '', // 申请人称
        reply: '', // 被申请人答复称
        thirequest: '', // 第三人称(空则传一个/)
        finding: '', // 经审理查明
        // 本机关认为
        think:
          '属于《中华人民共和国行政复议法实施条例》第四十八条第一款第xxxx项规定的情形。根据该条规定，本机关决定：驳回申请人的行政复议申请',
        statement: '申请人对本决定不服，可以自接到本决定之日起15日内，向xxxxxx人民法院提起行政诉讼', //符合行政诉讼受案范围 描述
      },
      statementText: '申请人对本决定不服，可以自接到本决定之日起15日内，向xxxxxx人民法院提起行政诉讼',
      isShowThird: true,
      isShowStatement: true,
      rules: {
        cause: [
          { required: true, message: '请输入案由', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        describe: [
          { required: true, message: '请输入申请意见', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        aplrequest: [
          { required: true, message: '请输入申请人请求', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        illustrate: [
          { required: true, message: '请输入申请人称', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        reply: [
          { required: true, message: '请输入被申请人答复称', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        finding: [
          { required: true, message: '请输入经审理查明', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        think: [
          { required: true, message: '请输入本机关认为', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
      },
      Tp_decision: Tp_decision,
      radioVal: true,
      // 申请人
      applicantColumns: [
        // 表头配置
        {
          title: '序号',
          align: 'center',
          width: "100px",
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '申请人',
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '性别',
          key: 'gender',
          dataIndex: 'gender',
          scopedSlots: { customRender: 'genderSlot' },
        },
        {
          title: '民族',
          key: 'nation',
          dataIndex: 'nation',
          scopedSlots: { customRender: 'nationSlot' },
        },
        {
          title: '出生年月',
          key: 'birthym',
          dataIndex: 'birthym',
        },
        {
          title: '住址',
          key: 'addr',
          dataIndex: 'addr',
          scopedSlots: { customRender: 'addrSlot' },
        }
      ],
      applylist: [],
      // 企业
      enterpriseColumns: [
        // 表头配置
        {
          title: '序号',
          align: 'center',
          width: "100px",
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '名称',
          key: 'name',
          dataIndex: 'name',
          scopedSlots: { customRender: 'nameSlot' },
        },
        {
          title: '住址',
          key: 'addr',
          dataIndex: 'addr',
          scopedSlots: { customRender: 'addrSlot' },
        },
        {
          title: '法定代表人',
          key: 'manager',
          dataIndex: 'manager',
        },
        {
          title: '职务',
          key: 'job',
          dataIndex: 'job',
        },
      ],
      aplentlist: [],
      targetName: '', //被申请人
      // 第三人
      thirdColumns: [
        {
          title: '序号',
          align: 'center',
          width: "100px",
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '第三人',
          key: 'name',
          dataIndex: 'name',
          scopedSlots: { customRender: 'nameSlot' },
        },
        {
          title: '住址',
          key: 'addr',
          dataIndex: 'addr',
          scopedSlots: { customRender: 'addrSlot' },
        },
      ],
      // 第三人数据
      thirdperlist: [],
      queryParam: {
        pageNumber: 1,
        pageSize: 500,
        sort: 'id',
        order: 'desc',
        f_applyid: '',
      },
      isResize: false,
      previewFileSrc: '',
      previewLoading:false,
    }
  },
  async created() {
    this.queryParam.f_applyid = this.applyid
    if (this.decisiontype == Tp_decisionValue.SUBREJECT) {
      this.infoForm.think = "属于《中华人民共和国行政复议法实施条例》第四十八条第一款第xxxx项规定的情形。根据该条规定，本机关决定：驳回申请人的行政复议请求"
    }
    await this.getApplicantlist()
    await this.getThirdPerson()
    this.getTargetName()
    this.builderPerson()
  },
  watch: {
    'infoForm.finding': {
      handler: function(newVal, oldVal) {
        // 当前的类型是公民类型
        this.infoForm.describe = "经审理查明：  " + newVal + "\n" + "本机关认为： " + this.infoForm.think
        if (this.$refs.caseHandleDecisionReject) {  
          this.$refs.caseHandleDecisionReject.validate()
        }
      },
      deep: true
    },
    'infoForm.think': {
      handler: function(newVal, oldVal) {
        // 当前的类型是公民类型
        this.infoForm.describe = "经审理查明： " + this.infoForm.finding + "\n" + "本机关认为：" + newVal
        if (this.$refs.caseHandleDecisionReject) {  
          this.$refs.caseHandleDecisionReject.validate()
        }
      },
      deep: true
    }
  },

  components: {
    Splitpanes,
    Pane,
  },
  methods: {
    init() {
      this.modalVisible = true
      this.labelTitle = this.Tp_decision[this.decisiontype].name
      this.resetForm()
      this.infoForm.cause = this.reason;
      this.$nextTick(() => {
        this.previewDecisionDoc()
      })
    },
    handleCancel() {
      this.resetForm()
      this.modalVisible = false
    },
    resetForm() {
      this.$nextTick(() => {
        this.$refs.caseHandleDecisionReject.resetFields()
      })
    },
    // 状态转换显示
    genderLable(val) {
      for (let key in Tp_genderList) {
        if (Tp_genderList[key].value == val) {
          return Tp_genderList[key].name
        }
      }
      return val
    },
    nationLable(val) {
      for (let key in Tp_nationList) {
        if (Tp_nationList[key].value == val) {
          return Tp_nationList[key].name
        }
      }
      return val
    },
    onChangeRadio(e) {
      if (e.target.value) {
        this.isShowStatement = true
      } else {
        this.isShowStatement = false
      }
    },
    builderPerson() {
      let persons = []
      if (this.applylist == null || this.applylist == undefined || this.applylist.length > 0) {
        this.applylist.forEach((item) => {
          persons.push(item.name)
        })
      }
      if (this.aplentlist == null || this.aplentlist == undefined || this.aplentlist.length > 0) {
        this.aplentlist.forEach((item) => {
          persons.push(item.name)
        })
      }
      if (this.thirdperlist == null || this.thirdperlist == undefined || this.thirdperlist.length > 0) {
        this.thirdperlist.forEach((item) => {
          persons.push(item.name)
        })
      }
      let personStr = persons.join('，')
      let copystatementText = this.statementText
      this.infoForm.statement = copystatementText.replace('申请人', personStr)
    },
    async getThirdPerson() {
      this.thirdperlist = []
      await getThirdPerson(this.queryParam).then((res) => {
        if (res.code == 0) {
          this.thirdperlist = res.data.records
          if (this.thirdperlist == null || this.thirdperlist == undefined || this.thirdperlist.length == 0) {
            this.isShowThird = false
            this.infoForm.thirequest = '/'
          } else {
            this.isShowThird = true
          }
        } else {
          this.thirdperlist = []
        }
      })
    },
    async getApplicantlist() {
      this.applylist = []
      this.aplentlist = []
      await getApplicantlist(this.queryParam).then((res) => {
        if (res.code == 0) {
          res.data.records.forEach((element) => {
            if (element.type == Tp_applicantValue.CITIZEN) {
              this.applylist.push(element)
            } else {
              this.aplentlist.push(element)
            }
          })
        } else {
          this.applylist = []
          this.aplentlist = []
        }
      })
    },
    getTargetName() {
      let queryParam = {
        pageNumber: 1,
        pageSize: 500,
        sort: 'id',
        order: 'desc',
        f_id: this.applyid,
      }
      getReviewList(queryParam).then((res) => {
        if (res.code == 0) {
          if (res.data.records != null && res.data.records != undefined && res.data.records.length > 0) {
            this.targetName = res.data.records[0].targetname
          }
        } else {
          this.targetName = ''
        }
      })
    },
    /**
     * 换行替换
     */
    trimLine(str) {
      return str ? str.replace(/(\r\n|\n|\r)/gm, '').replace(/^\s*|\s*$/g, '') : ''
    },
    /**
     * 提交表单
     */
    onSubmit() {
      this.$refs.caseHandleDecisionReject.validate((valid) => {
        this.loading = true
        if (valid) {
          console.log('submit!', this.infoForm)
          let params = {
            applyid: this.applyid, // applyid
            proctype: this.proctype, // 操作分类
            userid: this.currentUser.userId,
            username: this.currentUser.fullname,
            processinstanceid: this.processinstanceid, // 流程实例id
            cause: this.trimLine(this.infoForm.cause), // 案由
            describe: this.trimLine(this.infoForm.describe), // 行政复议申请
          }
          let docfield = {
            decisiontype: this.decisiontype, // 决定类型
            aplrequest: this.trimLine(this.infoForm.aplrequest), // 申请人请求
            illustrate: this.trimLine(this.infoForm.illustrate), // 申请人称
            reply: this.trimLine(this.infoForm.reply), // 被申请人答复称
            thirequest: this.infoForm.thirequest, // 第三人称(空则传一个/)
            finding: this.trimLine(this.infoForm.finding), // 经审理查明
            think: this.trimLine(this.infoForm.think), // 本机关认为
            statement: this.trimLine(this.infoForm.statement), //符合行政诉讼受案范围 描述
            applylist: this.applylist, // 申请人(公民)
            aplentlist: this.aplentlist, // 申请人(企业)
            thirdperlist: this.thirdperlist, // 第三人
            targetlist: this.targetName, // 被申请人
          }
          if (!this.isShowStatement) {
            docfield.statement = ''
          }
          if (!this.isShowThird) {
            docfield.thirequest = '/'
          }
          console.log('入参参数：' + params)
          startBusinessProced(params, docfield).then((res) => {
            if (res.code !== 0) {
              this.$message.error('操作失败')
            } else {
              this.$message.success('操作成功')
              this.$emit('reload')
              this.$emit('close')
              this.modalVisible = false
              this.autoToSonRouter(res.data)
            }
            this.loading = false
          })
        } else {
          this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            //console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    },
    resize() {
      this.isResize = true
    },
    resized() {
      this.isResize = false
    },
    previewDecisionDoc() {
      let _this = this
      let params = {
        applyid: _this.applyid, // applyid
        proctype: _this.proctype, // 操作分类
        userid: _this.currentUser.userId,
        username: _this.currentUser.fullname,
        processinstanceid: _this.processinstanceid, // 流程实例id
        cause: _this.trimLine(_this.infoForm.cause), // 案由
        describe: _this.trimLine(_this.infoForm.describe), // 行政复议申请
      }
      let docfield = {
        decisiontype: _this.decisiontype, // 决定类型
        aplrequest: _this.trimLine(_this.infoForm.aplrequest), // 申请人请求
        illustrate: _this.trimLine(_this.infoForm.illustrate), // 申请人称
        reply: _this.trimLine(_this.infoForm.reply), // 被申请人答复称
        thirequest: _this.infoForm.thirequest, // 第三人称(空则传一个/)
        finding: _this.trimLine(_this.infoForm.finding), // 经审理查明
        think: _this.trimLine(_this.infoForm.think), // 本机关认为
        statement: _this.trimLine(_this.infoForm.statement), //符合行政诉讼受案范围 描述
        applylist: _this.applylist, // 申请人(公民)
        aplentlist: _this.aplentlist, // 申请人(企业)
        thirdperlist: _this.thirdperlist, // 第三人
        targetlist: _this.targetName, // 被申请人
      }
      if (!this.isShowStatement) {
        docfield.statement = ''
      }
      if (!this.isShowThird) {
        docfield.thirequest = '/'
      }
      console.log('入参参数：' + params)
      this.previewLoading=true
      previewDecisionDoc(params, docfield).then((res) => {
        this.previewLoading=false
        renderAsync(res, this.$refs.file, null, {
          className: 'text-docx', //class name/prefix for default and document style classes
          inWrapper: true, //enables rendering of wrapper around document content
          ignoreWidth: false, //disables rendering width of page
          ignoreHeight: false, //disables rendering height of page
          ignoreFonts: false, //disables fonts rendering
          breakPages: true, //enables page breaking on page breaks
          ignoreLastRenderedPageBreak: true, //disables page breaking on lastRenderedPageBreak elements
          experimental: true, //enables experimental features (tab stops calculation)
          trimXmlDeclaration: true, //if true, xml declaration will be removed from xml documents before parsing
          useBase64URL: false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
          useMathMLPolyfill: true, //includes MathML polyfills for chrome, edge, etc.
          debug: false //enables additional logging
        }) // 渲染到页面
      })
    }

  },
}
</script>
        
<style lang="scss" scoped>

 .button-div {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e9e9e9;
    padding: 10px 16px;
    background: #fff;
    text-align: center;
    z-index: 1
  }
</style>
            